layui.use(['form', 'table', 'upload', 'element'], function () {
    var form = layui.form,
        layer = layui.layer,
        table = layui.table,
        $ = layui.$,
        upload = layui.upload,
        element = layui.element;

    element.init(); //初始化element

    /**
     * 初始化表单，要加上，不然刷新部分组件可能会不加载
     */
    form.render();

    // 当前弹出层，防止ID被覆盖
    var parentIndex = layer.index;

    //编辑器
    var E = window.wangEditor;
    var editor = new E('#editorContent');
    var imgName = []; //保存编辑器上传的图片名、封面图，用于记录相应的文章图片
    var imgSize = []; //保存编辑器上传的图片、封面图对应的大小

    var fileName = []; //保存文章上传的附件名

    //初始化
    $(function(){

        //初始化编辑器
        initEditor();

        var index = layer.load(2);

        //初始化标签列表
        var url = "/web/boTag/getAllTag";
        $.get(url, {}, function(data){
            layer.close(index);
            if(data.state == "200"){

                $("#initTagIcon").remove(); //移除加载图标

                var boTagList = data['boTagList'];
                var tagHtml = '';
                for(var i = 0; i < boTagList.length; i++){
                    tagHtml += '<input type="checkbox" name="boTagArr" value="' + boTagList[i].id + '" title="' + boTagList[i].name +'">';
                }
                $("#initTagList").append(tagHtml);

                //初始化标签完成后再初始化文章
                initBoArticle()

            }else{
                layer.msg(data.message, {icon:2});
            }
            form.render();
        });
    });

    //初始化文章
    function initBoArticle(){
        var id = $("#id").val();
        if(id != '' && id != null && id != undefined){
            var index = layer.load(2);
            var url = "/web/boArticle/getInfoById";
            $.get(url, {id: id}, function(data){
                layer.close(index);
                if(data.state == "200"){
                    $("#title").val(data.title);
                    $("#article_image").attr('src', '/article_image/' + data.img);
                    $("#articleImagePath").val(data.img);
                    if(data.isTop == '1'){
                        $("#isTopSwitch").attr("checked", "checked");
                        $("#isTop").val('1');
                    }
                    $("#readNum").val(data.readNum);
                    $("#praiseNum").val(data.praiseNum);
                    $("#remark").val(data.remark);

                    //附件
                    var fileHtml = "";
                    var boFileList = data.boFileList;
                    for(var j = 0; j < boFileList.length; j++){
                        fileHtml += '<p>' + boFileList[j].fileOrgname + '</p>';
                    }
                    $('#pre_file').append(fileHtml);

                    //标签
                    var boTagList = data.boTagList;
                    for(var i = 0; i < $('input[type=checkbox]').length; i++){
                        for(var j = 0; j < boTagList.length; j++){
                            if(boTagList[j].id == $($('input[type=checkbox]')[i]).val()){
                                $($('input[type=checkbox]')[i]).attr("checked", "checked");
                                break;
                            }
                        }
                    }


                    editor.txt.html(data.content);
                }else{
                    layer.msg(data.message, {icon:2});
                }
                form.render();
            })
        }
    }

    //监听提交
    form.on('submit(saveBtn)', function (data) {

        //设置编辑器内容
        data.field.content = editor.txt.html();

        //设置图片名记录
        data.field.imgName = imgName.toString();

        //设置图片大小记录
        data.field.imgSize = imgSize.toString();

        //获取选中的标签
        var boTagArr = [];
        $('input[type=checkbox]:checked').each(function() {
            boTagArr.push($(this).val());
        });
        //设置标签的值
        data.field.boTagArr = boTagArr.toString();

        if(boTagArr.toString() == '' || boTagArr.toString() == undefined || boTagArr.toString() == null){
            layer.msg("请选择标签", {icon:2, anim:6});
            return false;
        }

        var index = layer.load(2);
        var url = "/web/boArticle/save";
        $.post(url, data.field, function(res){
            if(res.state == "200"){
                layer.msg(res.message, {icon:1});
            }else{
                layer.msg(res.message, {icon:2});
            }
            // 关闭弹出层
            layer.close(index);
            layer.close(parentIndex);
        }, 'json');

        return false;
    });

    //点击取消
    $("#closeBtn").on("click", function(){
        deleteImgLog();
        deleteFile();
        // 关闭弹出层
        layer.close(parentIndex);
    });

    //点击右上角关闭
    $(".layui-layer-close1").on("click", function(){
        deleteImgLog();
        deleteFile();
        // 关闭弹出层
        layer.close(parentIndex);
    });

    //不保存，点击取消则删除编辑器已经上传的图片
    function deleteImgLog(){
        var url = "/web/boArticle/deleteImgLog";
        $.post(url, {
            imgName: imgName.toString()
        }, function(res){
            if(res.state == "200"){
                layer.msg(res.message, {icon:1});
            }else{
                layer.msg(res.message, {icon:2});
            }
        }, 'json');
    }

    //不保存，点击取消则删除已经上传的附件
    function deleteFile(){
        var url = "/web/boArticle/deleteFile";
        $.post(url, {
            serviceId: $('#serviceId').val()
        }, function(res){
            if(res.state == "200"){
                layer.msg(res.message, {icon:1});
            }else{
                layer.msg(res.message, {icon:2});
            }
        }, 'json');
    }

    //监听是否推荐开关
    form.on('switch(isTopSwitch)', function(data){
        if(data.elem.checked){
            $("#isTop").val("1"); //选中
        }else {
            $("#isTop").val("0");
        }
    });

    //封面图上传
    var uploadInst = upload.render({
        elem: '#imgBtn'
        ,url: '/web/boArticle/uploadArticleImg' //改成您自己的上传接口
        ,accept: 'images'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#article_image').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //上传成功
            if(res.state == "200"){
                imgName.push(res.fileName);
                imgSize.push(res.fileSize);
                $("#articleImagePath").val(res.fileName); //图片路径
                return layer.msg(res.message, {icon:1});
                //如果上传失败
            }else{
                return layer.msg(res.message, {icon:2});
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#article_image_text');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs head-reload">重试</a>');
            demoText.find('.head-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

    //编辑器
    function initEditor() {
        editor.customConfig.uploadImgServer = "/web/boArticle/uploadImg"; //图片上传地址
        editor.customConfig.uploadFileName = 'image';
        editor.customConfig.pasteFilterStyle = false;
        editor.customConfig.uploadImgMaxLength = 5; //一次最多上传图片数量
        editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 10M
        editor.customConfig.uploadImgHooks = {
            // 上传超时
            timeout: function (xhr, editor) {
                layer.msg('上传超时！')
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            customInsert: function (insertImg, result, editor) {
                if (result.state == "200") {
                    var url = result.url;
                    var imgItem = result.imgName;
                    var imgSizeItem = result.imgSize;
                    url.forEach(function (e) { //遍历显示预览图
                        insertImg(e);
                    });
                    imgItem.forEach(function (e) { //遍历保存图片名
                        imgName.push(e);
                    });
                    imgSizeItem.forEach(function (e) { //遍历保存大小
                        imgSize.push(e);
                    })
                } else {
                    layer.msg(result.message);
                }
            }
        };
        editor.customConfig.customAlert = function (info) {
            layer.msg(info);
        };
        editor.create();
    }

    //上传附件
    var fileNum = 0; //上传附件总数
    var fileCount = 0; //已成功上传的附件数量
    var uploadFile = upload.render({
        elem: '#uploadFileBtn'
        ,url: '/web/boArticle/uploadFile' //改成您自己的上传接口
        ,multiple: true //多文件上传
        ,accept: 'file'
        ,number: 20 //一次只能上传20附件
        ,acceptMime: 'file/*' //只显示文件
        ,auto: true //点击按钮才上传
        ,data: { //额外参数
            serviceId: function(){
                return $('#serviceId').val();
            }
        }
        ,choose: function(obj){ //选中预览
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                fileNum++;//上传附件总数
                $('#pre_file').append('<p>' + file.name + '</p>');

                var percent = fileCount + '/' + fileNum;
                $("#file-progress").attr('lay-percent', percent); //设置进度
                element.init(); //初始化element
            });

        }
        // ,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
        //     layer.load(2); //上传loading
        // }
        ,done: function(res){ //
            //上传成功
            if(res.state == "200"){
                fileCount ++;
                var percent = fileCount + '/' + fileNum;
                // element.progress('photo-progress', percent); //设置进度
                $("#file-progress").attr('lay-percent', percent); //设置进度
                element.init(); //初始化element
            }
        }
        ,allDone: function(obj){ //当文件全部被提交后，才触发
            layer.closeAll('loading'); //关闭加载层
            var text = '总附件数：' + obj.total + '<br/>上传成功：' + obj.successful + '<br/>上传失败：' + obj.aborted;
            layer.msg(text);
        }
    });

});